﻿using AutoMapper;
using FreeSql.Internal.Model;
using HuiLian.Common.Helpers;
using HuiLian.Common.Input;
using HuiLian.Common.Output;
using HuiLian.Model.Platform;
using HuiLian.Repository.Platform;
using HuiLian.Service.Platform.PipeTeZhengData.Input;
using HuiLian.Service.Platform.PipeTeZhengData.Output;
using NPOI.Util;
using Org.BouncyCastle.Utilities.Collections;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static FreeSql.Internal.GlobalFilter;

namespace HuiLian.Service.Platform.PipeTeZhengData
{
    /// <summary>
    /// 管网特征数据库服务
    /// </summary>
    public class PipeTeZhengDataService: IPipeTeZhengDataService
    {
        private readonly IMapper _mapper;
        private readonly IPipeTeZhengDataRepository _pipeTeZhengDataRepository;
        private readonly IRepairledgetRepository _repairledgetRepository;
        private readonly IPipeHealthRepository _pipeHealthRepository;
        private readonly IModelParamRepository _modelParamRepository;

        public PipeTeZhengDataService(
            IMapper mapper,
            IPipeTeZhengDataRepository pipeTeZhengDataRepository,
            IRepairledgetRepository repairledgetRepository,
            IPipeHealthRepository pipeHealthRepository,
            IModelParamRepository modelParamRepository)
        {
            _mapper = mapper;
            _pipeTeZhengDataRepository = pipeTeZhengDataRepository;
            _repairledgetRepository = repairledgetRepository;
            _pipeHealthRepository = pipeHealthRepository;
            _modelParamRepository = modelParamRepository;
        }

        /// <summary>
        /// 获取危险阈值
        /// </summary>
        /// <returns></returns>
        private async Task<double> GetWeiXianYuzhi()
        {
            double weiXianYuzhi = 0.9;
            var modelParam = await _modelParamRepository.Select.FirstAsync();
            if (modelParam != null)
            {
                weiXianYuzhi = modelParam.threshold;
            }
            return weiXianYuzhi;
        }

        /// <summary>
        /// 查询管网特征数据库信息
        /// </summary>
        /// <param name="input">分页信息</param>
        /// <returns></returns>
        public async Task<IResponseOutput> PageAsync(PageInput<PipeEntity> input)
        {
            //获取管线健康状态
            double weiXianYuzhi = await GetWeiXianYuzhi();
            //把管龄换算成竣工接收时间
            if (input.DynamicFilter != null)
            {
                foreach (var item in input.DynamicFilter.Filters)
                {
                    if(item.Field == "管龄")
                    {
                        item.Field = "竣工接收时间";

                        if (item.Operator == DynamicFilterOperator.GreaterThanOrEqual)
                        {
                            item.Operator = DynamicFilterOperator.LessThanOrEqual;
                            item.Value = DateTime.Now.AddYears(0 - item.Value.ToInt()).ToString("yyyy-12-31 23:59:59");
                        }
                        else if (item.Operator == DynamicFilterOperator.LessThanOrEqual)
                        {
                            item.Operator = DynamicFilterOperator.GreaterThanOrEqual;
                            item.Value = DateTime.Now.AddYears(0 - item.Value.ToInt()).ToString("yyyy-01-01 00:00:00");
                        }
                    }
                    else if(item.Field == "健康级别")
                    {
                        item.Field = "健康度";
                        var 健康级别 = item.Value;
                        switch(健康级别)
                        {
                            case "危险":
                                if (item.Operator == DynamicFilterOperator.GreaterThanOrEqual)
                                {
                                    item.Operator = DynamicFilterOperator.GreaterThan;
                                    item.Value = weiXianYuzhi;
                                }
                                else if(item.Operator == DynamicFilterOperator.LessThanOrEqual)
                                {
                                    item.Value = 1;
                                }
                                break;
                            case "较差":
                                if (item.Operator == DynamicFilterOperator.GreaterThanOrEqual)
                                {
                                    item.Operator = DynamicFilterOperator.GreaterThan;
                                    item.Value = 0.75;
                                }
                                else if(item.Operator == DynamicFilterOperator.LessThanOrEqual)
                                {
                                    item.Value = weiXianYuzhi;
                                }
                                break;
                            case "一般":
                                if (item.Operator == DynamicFilterOperator.GreaterThanOrEqual)
                                {
                                    item.Operator = DynamicFilterOperator.GreaterThan;
                                    item.Value = 0.5;
                                }
                                else if (item.Operator == DynamicFilterOperator.LessThanOrEqual)
                                {
                                    item.Value = 0.75;
                                }
                                break;
                            case "健康":
                                if (item.Operator == DynamicFilterOperator.GreaterThanOrEqual)
                                {
                                    item.Value = 0;
                                }
                                else if (item.Operator == DynamicFilterOperator.LessThanOrEqual)
                                {
                                    item.Value = 0.5;
                                }
                                break;
                            case "未知":
                                if (item.Operator == DynamicFilterOperator.GreaterThanOrEqual)
                                {
                                    item.Value = -2;
                                }
                                else if (item.Operator == DynamicFilterOperator.LessThanOrEqual)
                                {
                                    item.Value = -1;
                                }
                                break;
                        }
                    }
                }
            }

            var list = await _pipeTeZhengDataRepository.Select
            .WhereDynamicFilter(input.DynamicFilter)
            //.WhereIf(key.NotNull(), a => a.Path.Contains(key) || a.Label.Contains(key))
            .Count(out var total)
            .OrderByDescending(true, c => c.健康度)//健康度倒序
            .OrderBy(p => p.管段编号)
            .Page(input.CurrentPage, input.PageSize)
            .ToListAsync<PipeTeZhengDataListOutput>();

            foreach (var item in list)
            {
                //计算管龄,对于破损管线，是破损时间-竣工接收时间；对于普通管线，是当前时间-竣工接收时间
                item.管龄 = DateTime.Now.Year - item.竣工接收时间.ToDateTime().Year;//DateDiff函数
            }

            //获取管线健康状态
            //double weiXianYuzhi = await GetWeiXianYuzhi();

            foreach (var pipe in list)
            {
                pipe.健康级别 = PipeHelper.GetHealth(pipe.健康度, weiXianYuzhi);
            }

            var data = new PageOutput<PipeTeZhengDataListOutput>()
            {
                List = list,
                Total = total
            };
            return ResponseOutput.Ok(data);
        }

        /// <summary>
        /// 操作历史数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<IResponseOutput> OperationData(OperationDataInput input)
        {
            var list = await _repairledgetRepository.Select.Where(p => p.管段编号 == input.管段编号).ToListAsync<RepairledgetListOutput>();

            return ResponseOutput.Ok(list);
        }

        /// <summary>
        /// 统计各个健康级别的管线数量和管线长度
        /// </summary>
        /// <returns></returns>
        public async Task<IResponseOutput> StatisticsPipe(StatisticsPipeInput input)
        {
            StringBuilder sql = new StringBuilder();

            //获取管线健康状态
            double weiXianYuzhi = await GetWeiXianYuzhi();
            string whereSql = string.Empty;
            //geom的例子：POLYGON((12648168.47844 4129210.522,12648168.478 4126516.11679,12650977.539 4126477.89828,12650499.80 4128732.79,12648168.47844 4129210.522))
            if (!string.IsNullOrEmpty(input.geom))
            {
                whereSql = $@"where st_intersects(p.geom, ST_Transform(ST_GeomFromText('{input.geom}',3857),4547))";
            }

            sql.AppendLine(@$"  SELECT 健康级别,sum(管长) 管长,count(0) 数量 from (
 SELECT CASE

      WHEN 健康度 > {weiXianYuzhi} then '危险'

      WHEN 健康度 > 0.75 then '较差'

      WHEN 健康度 > 0.5 then '一般'

      WHEN 健康度 >= 0 then '健康'

      ELSE '未知'

      END as 健康级别, 管长
  FROM pipe p
     LEFT JOIN pipe_health h ON p.管段编号 = h.管段编号
{whereSql}
) a GROUP BY 健康级别 ");
            var result = await _pipeTeZhengDataRepository.Select.WithSql(sql.ToString()).ToListAsync<StatisticsPipeOutput>("健康级别,管长,数量");

            var sortArray = new List<string>() { "危险", "较差", "一般", "健康", "未知" };
            List<StatisticsPipeOutput> data = new List<StatisticsPipeOutput>();
            foreach (var item in sortArray)
            {
                var resultItem = result.Where(p => p.健康级别 == item).FirstOrDefault();
                if(resultItem != null) data.Add(resultItem); else {  data.Add(new StatisticsPipeOutput { 健康级别 = item, 数量 = 0, 管长 = 0}); }
            }

            return ResponseOutput.Ok(data);
        }
    }
}
